#pragma once

#include "lib.h"
#include "MyWindow.h"
#include "board.h"


MyWindow win;
bool quit;
SDL_Event e;
Board *board;
GameState gameState;
SDL_Texture *textTexture = nullptr,*endTexture = nullptr;


int initAll() {
	gameState = Setting;
	board = new Board(win);
	SDL_Color color{ 255,0,0 };
	try {
		win.init("5ziqi");
	} catch (const runtime_error &e) {
		cout << e.what() << endl;
		win.quit();
		return -1;
	}

	try {
		board->loadBoard(BOARD_FILE);
		board->loadChessman(WHITE_FILE, BLACK_FILE);
		textTexture = win.renderText("Press B to chose Black, W to White", TTF_FILE, color, 24);
	} catch (const runtime_error &e) {
		cout << e.what() << endl;
		win.quit();
		return -1;
	}
}


void input() {
	while (SDL_PollEvent(&e)) {
		//If user closes he window
		if (e.type == SDL_QUIT)
			quit = true;
		if (gameState == Setting) {
			if (e.type == SDL_KEYDOWN) {
				if (e.key.keysym.sym == SDLK_b) {
					board->setPlayerSide(B, W);
					gameState = Begining;
				} else if (e.key.keysym.sym == SDLK_w) {
					board->setPlayerSide(W,B);
					gameState = Begining;
				}else if(e.key.keysym.sym == SDLK_t) {
						board->setPlayerSide(B, W);
						board->setAnalysis(true);
						gameState = Begining;
				}
			}
		}
		else if (gameState == Begining) {
			if (e.type == SDL_MOUSEBUTTONDOWN) {
				if (e.button.button == SDL_BUTTON_LEFT)
					board->click();
			}
			if (e.type == SDL_KEYDOWN) {
				if (e.key.keysym.sym == SDLK_t) {
					board->analysisGames();
				}
			}
		}else {
			if (e.type == SDL_KEYDOWN || e.type == SDL_MOUSEBUTTONDOWN) {
				gameState = Setting;
				board->prepareForNext();
			}
		}
		
	}
}

void logic() {
	if (gameState == Begining) {
		if (board->yourTurn()) {
			board->play();
		}
		if (board->AITurn()) {
			board->AIPlaying();
		}
		if (board->end() != N) {
			endTexture = board->prepareForEndTexture();
			gameState = Ending;
			return;
		}
		board->exchange();
	}
}


void render() {
	win.clear();
	board->render();
	if (gameState == Setting) {
		win.draw(85, 65, textTexture);
	} else if (gameState == Ending) {
		win.draw(120, 200, endTexture);
	}
	win.present();
}

void release() {
	win.quit();
	SDL_DestroyTexture(textTexture);
}

void run() {
	initAll();
	while (!quit) {
		input();
		logic();
		render();
	}
	release();
}


int main(int args, char* argv[]) {

	run(); 
	return 0;
}